package com.potato.seckill.exception;

import java.util.List;

import javax.servlet.http.HttpServletRequest;

import com.potato.seckill.result.CodeMsg;
import com.potato.seckill.result.Result;
import org.springframework.validation.BindException;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;


/**
 * 自定义全局异常处理器
 */
@ControllerAdvice // 表明这个类是一个切面
@ResponseBody
public class GlobalExceptionHandler {
	@ExceptionHandler(value=Exception.class) // 表示出拦截的错误类型
	public Result<String> exceptionHandler(HttpServletRequest request, Exception e){
		e.printStackTrace();//打印异常到控台
		if(e instanceof GlobalException) { // 自定义的全局类型
			GlobalException ex = (GlobalException)e;
			return Result.error(ex.getCm());
		}else if(e instanceof BindException) { // jsr校验错误信息
			BindException ex = (BindException)e;
			List<ObjectError> errors = ex.getAllErrors();
			ObjectError error = errors.get(0);
			String msg = error.getDefaultMessage();
			return Result.error(CodeMsg.BIND_ERROR.fillArgs(msg));
		}else {
			return Result.error(CodeMsg.SERVER_ERROR);
		}
	}
}
